/**
 * Created by IntelliJ IDEA.
 * User: jiyufei
 * Date: 2018/11/19
 * Time: 10:00
 **/
package com.jiyufei.secure;

import com.jiyufei.redis.RedisCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SecureRedis {
    
    private RedisCenter redisCenter;
    private SecureSessionIdGenerator secureSessionIdGenerator;
    private String result;
    private Long sessionId,resLong;
    
    private final static Logger logger = LoggerFactory.getLogger(SecureRedis.class);
    
    public SecureRedis(){
        redisCenter = new RedisCenter();
        secureSessionIdGenerator = new SecureSessionIdGenerator();
    }
    
    public SecureRedis(int start){
        redisCenter = new RedisCenter();
        secureSessionIdGenerator = new SecureSessionIdGenerator(start);
    }
    
    /*
    * 读取sessionId,当不存在时，返回0
    * 成功读取后，自动更新time值
    *
    * key field "sessionId|unix时间戳"
    * */
    public Long getSessionId(String key,String field){
        result = redisCenter.getData(key,field);
        if(result == null){
            return 0L;
        }
        String sessionIdStr = result.split("\\|")[0];
        sessionId = Long.parseLong(sessionIdStr);
        //更新time
        
        long time = System.currentTimeMillis();
        String nowTimeStamp = String.valueOf(time / 1000);
        String value = sessionIdStr + "|" + String.valueOf(nowTimeStamp);
        resLong = redisCenter.setData(key,field,value);
        if(resLong == null){
            logger.error("[SecureRedis.getSessionId]时间更新失败! key:" + key + ",field:" + field);
        }
        
        return sessionId;
    }
    
    
    /*
    *设置sessionID和时间戳
    * 返回sessionId
    */
    public Long setSessionIdAndTime(String key,String field,long start){
        long time = System.currentTimeMillis();
        String nowTimeStamp = String.valueOf(time / 1000);
        
        //sessionId = secureSessionIdGenerator.nowData(start);
        sessionId = secureSessionIdGenerator.getSessionId();
        String value = String.valueOf(sessionId) + "|" + String.valueOf(nowTimeStamp);
        resLong = redisCenter.setData(key,field,value);
        if(resLong == 1L){
            return sessionId;
        }
        logger.info("[SecureRedis.setSessionIdAndTime]在redis中写入sessionId有误！返回值：" + resLong + ",key:" + key + ",field:" + field);
        return resLong;
    }
    
    
    
}
